import binascii
from .gmssl import func, sm2, sm3

class Sm2Key(sm2.CryptSM2):

    def __init__(self, private_key):
        sm2.CryptSM2.__init__(self, '', '')

        if private_key is None:
            self.private_key = func.random_hex(64)
        else:
            self.private_key = private_key
        
        self.public_key = self._kg(int(self.private_key, 16), self.ecc_table['g'])

        public_key_hash = sm3.sm3_hash(func.bytes_to_list(binascii.a2b_hex(self.public_key)))
        self.address = public_key_hash[24:]

    def sign_rsv(self, data):
        sign_data = binascii.a2b_hex(data)
        signature = None

        while signature is None:
            k = func.random_hex(self.para_len)
            signature = self.sign(sign_data, k)

        return signature
    
    def sign_rsv_with_sm3(self, data):
        data = sm3.sm3_hash(func.bytes_to_list(binascii.a2b_hex(data)))
        return self.sign_rsv(data)
